import { useEffect, useState } from "react";
import {
	Card,
	Table,
	Button,
	message,
	Tag,
	Space,
	Modal,
	Tooltip,
	Image,
	Form,
	Input,
	Select,
	Switch,
} from "antd";

import type { ColumnsType } from "antd/es/table";
import { PlusOutlined } from "@ant-design/icons";
import { Iconify } from "@/components/icon";
import UserModal from "./user-modal";
import userService, { UserItem } from "@/api/services/userService";
import dayjs from "dayjs";

export default function UserList() {
	const [loading, setLoading] = useState(false);
	const [users, setUsers] = useState<UserItem[]>([]);
	const [total, setTotal] = useState(0);
	const [modalOpen, setModalOpen] = useState(false);
	const [currentUser, setCurrentUser] = useState<UserItem | null>(null);
	const [detailModalOpen, setDetailModalOpen] = useState(false);
	const [form] = Form.useForm();

	const columns: ColumnsType<UserItem> = [
		{
			title: "ID",
			dataIndex: "id",
			width: 80,
		},
		{
			title: "手机号",
			dataIndex: "mobile",
			width: 120,
		},
		{
			title: "昵称",
			dataIndex: "nickname",
		},
		{
			title: "公司",
			dataIndex: "company",
		},
		{
			title: "状态",
			dataIndex: "status",
			width: 100,
			render: (status: number, record) => (
				<Switch
					checked={status === 1}
					checkedChildren="正常"
					unCheckedChildren="禁用"
					onChange={(checked) => {
						Modal.confirm({
							title: "确认提示",
							content: `确定要${checked ? "启用" : "禁用"}该用户吗？`,
							onOk: () => handleChangeStatus(record),
						});
					}}
				/>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			render: (createtime) => (
				<span>{dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
			),
		},
		{
			title: "操作",
			key: "action",
			width: 200,
			render: (_, record) => (
				<Space>
					<Tooltip title="查看详情">
						<Button
							type="text"
							icon={<Iconify icon="mdi:eye-outline" />}
							onClick={() => handleViewDetail(record)}
						/>
					</Tooltip>
					{/* <Tooltip title="编辑">
						<Button
							type="text"
							icon={<Iconify icon="material-symbols:edit-outline" />}
							onClick={() => handleEdit(record)}
						/>
					</Tooltip>
					<Tooltip title="删除">
						<Button
							type="text"
							icon={<Iconify icon="material-symbols:delete-outline" />}
							onClick={() => handleDelete(record)}
						/>
					</Tooltip> */}
				</Space>
			),
		},
	];

	const fetchUsers = async (params?: any) => {
		try {
			setLoading(true);
			const data = await userService.userList(params);
			setUsers(data.items);
			setTotal(data.total);
		} catch (error: any) {
			message.error(error.message);
		} finally {
			setLoading(false);
		}
	};

	const handleAdd = () => {
		setCurrentUser(null);
		setModalOpen(true);
	};

	const handleEdit = (record: UserItem) => {
		setCurrentUser(record);
		setModalOpen(true);
	};

	const handleViewDetail = (record: UserItem) => {
		setCurrentUser(record);
		setDetailModalOpen(true);
	};

	const handleDelete = async (record: UserItem) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除该用户吗？",
			onOk: async () => {
				try {
					await userService.userDelete(record.id);
					message.success("删除成功");
					fetchUsers();
				} catch (error) {
					message.error("删除失败");
				}
			},
		});
	};

	const handleChangeStatus = async (record: UserItem) => {
		try {
			const newStatus = record.status === 1 ? 0 : 1;
			await userService.userChangeStatus({
				id: record.id,
				status: newStatus,
			});
			message.success("状态修改成功");
			fetchUsers(form.getFieldsValue());
		} catch (error: any) {
			message.error(error.message);
		}
	};

	const handleSearch = async (values: any) => {
		await fetchUsers(values);
	};

	useEffect(() => {
		fetchUsers();
	}, []);

	return (
		<Card>
			<Form
				form={form}
				layout="inline"
				onFinish={handleSearch}
				style={{ marginBottom: 16 }}
			>
				<Form.Item name="mobile" label="手机号">
					<Input placeholder="请输入手机号" allowClear />
				</Form.Item>
				<Form.Item name="nickname" label="昵称">
					<Input placeholder="请输入昵称" allowClear />
				</Form.Item>
				<Form.Item name="company" label="公司名称">
					<Input placeholder="请输入公司名称" allowClear />
				</Form.Item>
				<Form.Item name="status" label="状态">
					<Select
						placeholder="请选择状态"
						allowClear
						style={{ width: 120 }}
						options={[
							{ label: "正常", value: 1 },
							{ label: "禁用", value: 0 },
						]}
					/>
				</Form.Item>
				<Form.Item>
					<Button type="primary" htmlType="submit">
						搜索
					</Button>
					<Button
						style={{ marginLeft: 8 }}
						onClick={() => {
							form.resetFields();
							fetchUsers();
						}}
					>
						重置
					</Button>
				</Form.Item>
			</Form>

			<div style={{ marginBottom: 16 }}>
				<Button
					type="primary"
					icon={<PlusOutlined />}
					onClick={() => {
						setCurrentUser(null);
						setModalOpen(true);
					}}
				>
					新增
				</Button>
			</div>

			<Table
				columns={columns}
				dataSource={users}
				rowKey="id"
				loading={loading}
				pagination={{
					total,
					showSizeChanger: true,
					showQuickJumper: true,
					showTotal: (total) => `共 ${total} 条`,
				}}
			/>

			<UserModal
				open={modalOpen}
				onCancel={() => setModalOpen(false)}
				user={currentUser}
				onSuccess={() => {
					setModalOpen(false);
					fetchUsers();
				}}
			/>

			<Modal
				title="用户详情"
				open={detailModalOpen}
				onCancel={() => setDetailModalOpen(false)}
				footer={null}
				width={800}
			>
				{currentUser && (
					<div className="space-y-4">
						<div className="flex items-center">
							<span className="w-24 font-medium">昵称：</span>
							<span className="text-gray-900">{currentUser.nickname}</span>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">手机号：</span>
							<span className="text-gray-900">{currentUser.mobile}</span>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">公司：</span>
							<span className="text-gray-900">
								{currentUser.company || "-"}
							</span>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">支付宝账号：</span>
							<span className="text-gray-900">
								{currentUser.alipay_account || "-"}
							</span>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">状态：</span>
							<Tag color={currentUser.status === 1 ? "success" : "error"}>
								{currentUser.status === 1 ? "正常" : "禁用"}
							</Tag>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">创建时间：</span>
							<span className="text-gray-900">
								{dayjs(currentUser.createtime * 1000).format(
									"YYYY-MM-DD HH:mm:ss",
								)}
							</span>
						</div>
						<div className="flex items-center">
							<span className="w-24 font-medium">更新时间：</span>
							<span className="text-gray-900">
								{dayjs(currentUser.updatetime * 1000).format(
									"YYYY-MM-DD HH:mm:ss",
								)}
							</span>
						</div>
						{currentUser.remark && (
							<div className="flex items-center">
								<span className="w-24 font-medium">备注：</span>
								<span className="text-gray-900">{currentUser.remark}</span>
							</div>
						)}
						<div className="flex items-start">
							<span className="w-24 font-medium mt-1">营业执照：</span>
							<div>
								{currentUser.business_license_img ? (
									<Image
										src={currentUser.business_license_img}
										alt="营业执照"
										width={200}
										className="object-contain"
									/>
								) : (
									<span className="text-gray-900">-</span>
								)}
							</div>
						</div>
						<div className="flex items-start">
							<span className="w-24 font-medium mt-1">工作室门头照</span>
							<div>
								{currentUser.website_logo ? (
									<Image
										src={currentUser.website_logo}
										alt="工作室门头照"
										width={200}
										className="object-contain"
									/>
								) : (
									<span className="text-gray-900">-</span>
								)}
							</div>
						</div>
						<div className="flex items-start">
							<span className="w-24 font-medium mt-1">微信二维码：</span>
							<div>
								{currentUser.wechat_qr_code_img ? (
									<Image
										src={currentUser.wechat_qr_code_img}
										alt="微信二维码"
										width={200}
										className="object-contain"
									/>
								) : (
									<span className="text-gray-900">-</span>
								)}
							</div>
						</div>
						<div className="flex items-start">
							<span className="w-24 font-medium mt-1">支付宝二维码：</span>
							<div>
								{currentUser.alipay_qr_code_img ? (
									<Image
										src={currentUser.alipay_qr_code_img}
										alt="支付宝二维码"
										width={200}
										className="object-contain"
									/>
								) : (
									<span className="text-gray-900">-</span>
								)}
							</div>
						</div>
					</div>
				)}
			</Modal>
		</Card>
	);
}
